package com.cloud.aop;

import com.cloud.constant.SystemConstant;
import com.cloud.model.system.SysErrorLog;
import com.cloud.model.system.SysOperationLog;
import com.cloud.model.system.SysUser;
import com.cloud.service.SysErrorLogService;
import com.cloud.service.SysLogService;
import com.cloud.utils.DateUtil;
import com.cloud.utils.Result;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;

/**
 * Created by Administrator on 2017/11/13 0013.
 */
@Aspect
@Component
public class SystemLog {
    Logger logger = LoggerFactory.getLogger(SystemLog.class);
    @Autowired
    private SysLogService sysLogService;
    @Autowired
    private SysErrorLogService sysErrorLogService;

    @Pointcut("execution(public com.cloud.utils.Result  com.cloud.controller.*.*(..))")
    public void pointCut() {
    }

    @Pointcut("execution(public * com.cloud.controller.*.*(..)))")
    public void errorCut() {

    }

    @AfterReturning(pointcut = "pointCut()", returning = "object")
    public void writeLogAfterExecute(JoinPoint joinPoint, Object object) {
        SysOperationLog sysLog = new SysOperationLog();
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        SysUser user = (SysUser) request.getSession().getAttribute(SystemConstant.SESSION_USER);
        if (user != null) {
            sysLog.setOperater(user.getUserName());
        }
        // ip
        sysLog.setIp(request.getRemoteAddr());
        // 请求的方法----操作的内容
        sysLog.setMethod(joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName());
        if (object instanceof Result) {
            Result result = (Result) object;
            sysLog.setOperation(result.getMsg());
            // 结果
            if (result.isSuccess()) {
                sysLog.setResult("操作成功");
            } else {
                sysLog.setResult("操作失败");
            }
            this.sysLogService.saveLog(sysLog);
        }
    }

    /**
     * 记录系统出错的日志到数据库
     *
     * @param joinPoint
     * @param e
     */
    @AfterThrowing(pointcut = "errorCut()", throwing = "e")
    public void recordSystemErrorLog(JoinPoint joinPoint, Throwable e) {
        SysErrorLog errorLog = new SysErrorLog();
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        SysUser user = (SysUser) request.getSession().getAttribute(SystemConstant.SESSION_USER);
        if (user != null) {
            errorLog.setUserName(user.getUserName());
        }
        errorLog.setIp(request.getRemoteAddr());
        errorLog.setOperateTime(DateUtil.getCurrentDateTimeStr());
        errorLog.setUrl(request.getRequestURL().toString());
        errorLog.setClassMethod(joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName());
        errorLog.setMethod(request.getMethod());
        errorLog.setArgs(Arrays.toString(joinPoint.getArgs()));
        errorLog.setException(e.getMessage());
        sysErrorLogService.saveLog(errorLog);
    }
}
